package com.hsq.jdbc.mysql;

import com.hsq.jdbc.utils.JDBCUtils;
import com.mysql.cj.PreparedQuery;
import com.mysql.cj.QueryBindings;
import com.mysql.cj.exceptions.CJException;
import com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping;
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.concurrent.locks.Lock;

public class BatchTest {


    @Test
    public void testBatch() throws Exception {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into admin values(?, ?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        System.out.println("开始执行");
        long start = System.currentTimeMillis();
        for (int i = 1; i <= 5000; i ++) {
            preparedStatement.setString(1, "tom" + 1);
            preparedStatement.setInt(2, i);
//            preparedStatement.executeUpdate();
            //使用批量处理必须在mysql.properties 文件中加入 ?rewriteBatchedStatements=true
            /*
            1.第一个数据就创建ArrayList - elementData =>> Object[]
            2.element =>> Object[] 就会存放我们预处理的sql语句
            3.当elementData满后，按照1.5倍扩容
            4.当到达我们自己设定的值后就执行executeBatch
            5.批量处理会减少我们发送sql语句网络的开销，而且减少编译次数，因此效率提高
            public void addBatch() throws SQLException {
                try {
                    Lock connectionLock = this.checkClosed().getConnectionLock();
                    connectionLock.lock();

                    try {
                        QueryBindings queryBindings = ((PreparedQuery)this.query).getQueryBindings();
                        queryBindings.checkAllParametersSet();
                        this.query.addBatch(queryBindings.clone());
                    } finally {
                        connectionLock.unlock();
                    }

                } catch (CJException var8) {
                    throw SQLExceptionsMapping.translateException(var8, this.getExceptionInterceptor());
                }
            }
            */
            preparedStatement.addBatch();//执行sql语句
            if (i % 1000 == 0) {
                //满1000时执行批量处理
                preparedStatement.executeBatch();
                //清空批量处理
                preparedStatement.clearBatch();
            }
        }
        System.out.println("执行结束");
        long end = System.currentTimeMillis();
        System.out.println("批量处理耗时：" + (end - start));
        JDBCUtils.close(null, preparedStatement, connection);
    }
}
